//동영상 플레이어

package com.ibk.system.media;

import com.ibk.system.R;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

public class VodPlayerViewActivity extends Activity implements OnCompletionListener,
		MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener,
		SurfaceHolder.Callback {
	// 동영상 주소
	private String LINK;

	private MediaPlayer m_MediaPlayer;
	private VodPlayerSurfaceView m_Surface;
	private SurfaceHolder m_SurfaceHolder;

	private boolean isPaused = false; // 일시정지
	private boolean isEnd = false; // 동영상이 끝까지 다 재생됐는지

	private View m_Controller = null; // 플레이어 콘트롤러(재생, 정지, 앞으로, 뒤로, 시간)
	private long m_ControllerActionTime = 0L; // 화면에 컨트롤러가 보이고 사라지는 시간을 제는대 사용

	private int m_iVideoPlayTime = 0; // 동영상 플레이 길이(시간 1000/1초)
	private int m_iSkipTime = 5000; // 스킵 시간(1000=1초)
	private SeekBar m_TimeBar = null; // 볼륨바
	private SeekBar m_VolumeBar = null; // 재생바
	private ImageButton m_PlayButton = null; // 재생, 정지
	private ImageButton m_SkipPrev = null; // 뒤로
	private ImageButton m_SkipNext = null; // 앞으로
	private ProgressBar m_LoadingProgress = null; // 로딩프로그레스
	private TextView m_txtCurrentPlayTime = null; // 현제 재생시간 텍스트
	private TextView m_txtMaxPlayTime = null; // 전체 재생 시간 텍스트

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.video_player);

		LINK = getIntent().getStringExtra("url");
		if (LINK == null) {
			LINK = "http://ms.ibk.co.kr:7170/mov/oneclick0301a.mp4";
		}
		m_Surface = (VodPlayerSurfaceView) findViewById(R.id.surface);
		m_Surface.addTapListener(onTap);
		m_SurfaceHolder = m_Surface.getHolder();
		m_SurfaceHolder.addCallback(this);
		m_SurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		m_Controller = findViewById(R.id.bottom_panel);
		m_TimeBar = (SeekBar) findViewById(R.id.timeline);
		m_TimeBar.setOnSeekBarChangeListener(onTimeBarSkip);
		m_VolumeBar = (SeekBar) findViewById(R.id.vodplayer_volume);
		m_VolumeBar.setOnSeekBarChangeListener(onVolume);
		m_LoadingProgress = (ProgressBar) findViewById(R.id.vodplayer_loading_progress);
		m_LoadingProgress.setVisibility(View.VISIBLE);

		m_txtCurrentPlayTime = (TextView) findViewById(R.id.text_playtime_current);
		m_txtMaxPlayTime = (TextView) findViewById(R.id.text_playtime_max);

		AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		int iCurrentVolume = mAudioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		m_VolumeBar.setProgress(iCurrentVolume);

		m_PlayButton = (ImageButton) findViewById(R.id.button_play_pause);
		m_PlayButton.setOnClickListener(onPlayPause);
		m_SkipPrev = (ImageButton) findViewById(R.id.button_play_prev);
		m_SkipPrev.setOnClickListener(onSkipPreve);
		m_SkipNext = (ImageButton) findViewById(R.id.button_play_next);
		m_SkipNext.setOnClickListener(onSkipNext);
	}

	@Override
	protected void onResume() {
		isPaused = false;
		isEnd = false;
		m_Surface.postDelayed(onEverySecond, 1000);
		super.onResume();
	}

	@Override
	protected void onPause() {
		isPaused = true;
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (m_MediaPlayer != null) {
			m_MediaPlayer.release();
			m_MediaPlayer = null;
		}
		m_Surface.removeTapListener(onTap);
		super.onDestroy();
	}

	public void onCompletion(MediaPlayer arg0) {
		// finish();
	}

	// 동영상 재생준비 완료
	public void onPrepared(MediaPlayer mediaplayer) {
		int width = m_MediaPlayer.getVideoWidth();
		int height = m_MediaPlayer.getVideoHeight();

		m_SurfaceHolder.setFixedSize(width, height);
		m_iVideoPlayTime = m_MediaPlayer.getDuration();
		m_TimeBar.setMax(m_iVideoPlayTime);
		m_TimeBar.setProgress(0);
		m_TimeBar.setSecondaryProgress(0);
		SetTextTime(m_txtMaxPlayTime, m_iVideoPlayTime);

		m_MediaPlayer.start();
		m_ControllerActionTime = SystemClock.elapsedRealtime();
		m_Controller.setVisibility(View.VISIBLE);
		m_VolumeBar.setVisibility(View.VISIBLE);
		m_LoadingProgress.setVisibility(View.GONE);
	}

	public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
	}

	public void surfaceDestroyed(SurfaceHolder surfaceholder) {
	}

	// 재생준비 완료
	public void surfaceCreated(SurfaceHolder holder) {
		playVideo(LINK);
		clearPanels();
	}

	private void playVideo(String url) {
		try {
			if (m_MediaPlayer == null) {
				m_MediaPlayer = new MediaPlayer();
				m_MediaPlayer.setScreenOnWhilePlaying(true);
			} else {
				m_MediaPlayer.stop();
				m_MediaPlayer.reset();
			}

			isEnd = false;
			m_MediaPlayer.setDataSource(url);
			m_MediaPlayer.setDisplay(m_SurfaceHolder);
			m_MediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			m_MediaPlayer.setOnPreparedListener(this);
			m_MediaPlayer.prepareAsync();
			m_MediaPlayer.setOnCompletionListener(this);
			m_MediaPlayer.setOnBufferingUpdateListener(this);
			m_LoadingProgress.setVisibility(View.VISIBLE);
		} catch (Throwable t) {
		}
	}

	private void clearPanels() {
		m_ControllerActionTime = 0;
		m_Controller.setVisibility(View.GONE);
		m_VolumeBar.setVisibility(View.GONE);
	}

	// 전체 재생시간 텍스트 표시
	private void SetTextTime(TextView view, int time) {
		int hour = time / 360000; // 시간
		time %= 360000;
		int minute = time / 60000; // 분
		time %= 60000;
		int second = time / 1000; // 초

		String h = (hour < 10) ? "0" + Integer.toString(hour) : Integer
				.toString(hour);
		String m = (minute < 10) ? "0" + Integer.toString(minute) : Integer
				.toString(minute);
		String s = (second < 10) ? "0" + Integer.toString(second) : Integer
				.toString(second);
		view.setText(h + ":" + m + ":" + s);
	}

	// 화면 터치
	private VodPlayerSurfaceView.TapListener onTap = new VodPlayerSurfaceView.TapListener() {
		public void onTap(MotionEvent event) {
			m_ControllerActionTime = SystemClock.elapsedRealtime();
			if (m_Controller.getVisibility() == View.VISIBLE) // 메뉴 숨기기
				clearPanels();
			else // 메뉴 보이기
			{
				m_Controller.setVisibility(View.VISIBLE);
				m_VolumeBar.setVisibility(View.VISIBLE);
			}
		}
	};

	private Runnable onEverySecond = new Runnable() {
		public void run() {
			// 컨트롤러는 일정 시간후 사라지게 (1000=1초)
			if (m_ControllerActionTime > 0
					&& SystemClock.elapsedRealtime() - m_ControllerActionTime > 5000)
				clearPanels();
			if (m_MediaPlayer != null) {
				int time = m_MediaPlayer.getCurrentPosition();
				m_TimeBar.setProgress(time);
				SetTextTime(m_txtCurrentPlayTime, time);
			}
			if (!isPaused)
				m_Surface.postDelayed(onEverySecond, 1000);
		}
	};

	// 재생, 정지 버튼
	private View.OnClickListener onPlayPause = new View.OnClickListener() {
		public void onClick(View v) {
			m_ControllerActionTime = SystemClock.elapsedRealtime();

			if (m_MediaPlayer != null) {
				if (m_MediaPlayer.isPlaying())// 재생 중이면
				{
					m_PlayButton.setImageResource(R.drawable.bt_play);
					m_MediaPlayer.pause();
				} else // 재생중이지 안으면
				{
					m_PlayButton.setImageResource(R.drawable.bt_stop);
					if (isEnd) {
						playVideo(LINK);
						clearPanels();
					} else
						m_MediaPlayer.start();
				}
			}
		}
	};

	// 뒤로 스킵버튼
	private View.OnClickListener onSkipPreve = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			int time = m_MediaPlayer.getCurrentPosition() - m_iSkipTime;
			if (time < 0)
				time = 0;
			m_MediaPlayer.seekTo(time);
		}
	};

	// 앞으로 스킵버튼
	private View.OnClickListener onSkipNext = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			int time = m_MediaPlayer.getCurrentPosition() + m_iSkipTime;
			if (time > m_iVideoPlayTime)
				time = m_iVideoPlayTime;
			m_MediaPlayer.seekTo(time);
		}
	};

	// 플레이 타임바
	private SeekBar.OnSeekBarChangeListener onTimeBarSkip = new SeekBar.OnSeekBarChangeListener() {
		@Override
		public void onProgressChanged(SeekBar seekbar, int i, boolean flag) {
			if (flag)
				m_MediaPlayer.seekTo(i);
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekbar) {
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekbar) {
		}
	};

	// 볼륨바
	private SeekBar.OnSeekBarChangeListener onVolume = new SeekBar.OnSeekBarChangeListener() {
		@Override
		public void onProgressChanged(SeekBar seekbar, int i, boolean flag) {
			if (flag) {
				AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
				// int maxVolume =
				// mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
						(i / 2), AudioManager.FLAG_PLAY_SOUND);
			}
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekbar) {
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekbar) {
		}
	};

	// 버퍼링 표시
	@Override
	public void onBufferingUpdate(MediaPlayer mediaplayer, int i) {
		// i=100%로 넘어옴
		// 퍼센트지로 표시
		m_TimeBar.setSecondaryProgress((m_iVideoPlayTime / 100) * i);
	}

	// 뒤로가기 버튼
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (m_Controller.getVisibility() == View.VISIBLE) // 메뉴 숨기기
				clearPanels();
			else
				finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
